// Copyright Epic Games, Inc. All Rights Reserved.

#include "trace_cmd.h"
#include <zencore/logging.h>
#include <zenhttp/httpclient.h>
#include <zenhttp/httpcommon.h>

using namespace std::literals;

namespace zen {

TraceCommand::TraceCommand()
{
	m_Options.add_options()("h,help", "Print help");
	m_Options.add_option("", "u", "hosturl", "Host URL", cxxopts::value(m_HostName)->default_value(""), "<hosturl>");
	m_Options.add_option("", "s", "stop", "Stop tracing", cxxopts::value(m_Stop)->default_value("false"), "<stop>");
	m_Options.add_option("", "", "host", "Start tracing to host", cxxopts::value(m_TraceHost), "<hostip>");
	m_Options.add_option("", "", "file", "Start tracing to file", cxxopts::value(m_TraceFile), "<filepath>");
}

TraceCommand::~TraceCommand() = default;

int
TraceCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
	ZEN_UNUSED(GlobalOptions);

	if (!ParseOptions(argc, argv))
	{
		return 0;
	}

	m_HostName = ResolveTargetHostSpec(m_HostName);

	if (m_HostName.empty())
	{
		throw OptionParseException("unable to resolve server specification");
	}

	zen::HttpClient Http(m_HostName);

	if (m_Stop)
	{
		if (zen::HttpClient::Response Response = Http.Post("/admin/trace/stop"sv))
		{
			ZEN_CONSOLE("OK: {}", Response.ToText());
			return 0;
		}
		else
		{
			ZEN_ERROR("trace stop failed: {}", Response.ToText());
			return 1;
		}
	}

	std::string StartArg;
	if (!m_TraceHost.empty())
	{
		StartArg = fmt::format("host={}", m_TraceHost);
	}
	else if (!m_TraceFile.empty())
	{
		StartArg = fmt::format("file={}", m_TraceFile);
	}

	if (!StartArg.empty())
	{
		if (zen::HttpClient::Response Response = Http.Post(fmt::format("/admin/trace/start?{}"sv, StartArg)))
		{
			ZEN_CONSOLE("OK: {}", Response.ToText());
			return 0;
		}
		else
		{
			ZEN_ERROR("trace start failed: {}", Response.ToText());
			return 1;
		}
	}

	if (zen::HttpClient::Response Response = Http.Get("/admin/trace"sv))
	{
		ZEN_CONSOLE("OK: {}", Response.ToText());
		return 0;
	}
	else
	{
		ZEN_ERROR("trace status failed: {}", Response.ToText());
	}

	return 1;
}

}  // namespace zen
